/*
 * @Author: szx
 * @Date: 2022-03-07 13:52:03
 * @LastEditTime: 2022-03-07 13:56:33
 * @Description:
 * @FilePath: \leetcode\500-599\501\501_2.js
 */
function TreeNode(val, left, right) {
    this.val = val === undefined ? 0 : val;
    this.left = left === undefined ? null : left;
    this.right = right === undefined ? null : right;
}

/**
 * @param {TreeNode} root
 * @return {number[]}
 */
var findMode = function (root) {
    let prev = null;
    let res = [root.val];
    let cnt = 1;
    let max = 1;
    const dfs = (root) => {
        if (!root) return;
        if (root.left) dfs(root.left);
        if (prev) {
            if (prev.val == root.val) {
                cnt++;
                if (cnt > max) {
                    max = cnt;
                    res = [root.val];
                } else if (cnt == max) {
                    res.push(prev.val);
                }
            } else {
                cnt = 1;
            }
        }
        prev = root;
        if (root.right) dfs(root.right);
    };
    dfs(root);
    return res;
};
